package com.woniuxy.service.impl;

import com.woniuxy.mapper.AccountMapper;
import com.woniuxy.mapper.TranRecordMapper;
import com.woniuxy.pojo.Account;
import com.woniuxy.pojo.TranRecord;
import com.woniuxy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private TranRecordMapper tranRecordMapper;
    @Override
    public void transfer(String fromAccountno, String toAccountno, float money) throws IOException {
        /**
         * 转账的步骤
         * 1.查找对方的账户是否存在
         * 2.查询自己的账户
         */
        Account toAccount=accountMapper.selectAccountByAccountno(toAccountno);
        Account fromAccount=accountMapper.selectAccountByAccountno(fromAccountno);
        //转出指定的金额
        accountMapper.updateBalaneByAccount(fromAccountno,fromAccount.getBalance()-money);
        //此处模拟一个异常
        int i=10/0;
        //转入金额
        accountMapper.updateBalaneByAccount(toAccountno,toAccount.getBalance()+money);
        //转出者的动账记录
        TranRecord fromTranRecord=new TranRecord();
        fromTranRecord.setType(-1);
        fromTranRecord.setMoney(money);
        fromTranRecord.setMessage(fromAccountno+"转出"+money+"元");
        tranRecordMapper.addRecord(fromTranRecord);
        //转入者动账记录
        TranRecord toTranRecord=new TranRecord();
        toTranRecord.setType(1);
        toTranRecord.setMoney(money);
        toTranRecord.setMessage(toAccountno+"转入"+money+"元");
        tranRecordMapper.addRecord(toTranRecord);
    }
}
